<template>
  <div class="outer-order-page">
    <el-button type="primary" @click="saveAll">保存</el-button>
    <!-- 基本信息部分 -->
    <br/><br/>
    <el-card title="基本信息">
      <el-form 
        :model="form" 
        label-width="120px" 
        ref="formRef" 
        :rules="rules"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="生产工序名称" prop="processName">
              <el-input v-model="form.processName" required></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产工序编号" prop="processNumber">
              <el-input placeholder="保存后自动生成" disabled v-model="form.processNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产工序类别">
              <el-select v-model="form.processType" placeholder="请选择" required>
                <el-option label="设备生产工序" value="设备生产工序"></el-option>
                <el-option label="食品生产工序" value="食品生产工序"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="产能主体" label-width="140px">
              <el-radio-group v-model="form.capacityBody" required>
                <el-radio :label="false">设备</el-radio>
                <el-radio :label="true">人员</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
          <el-form-item label="*工序负责人" prop="processPerson">
            <el-input
                v-model="form.processPerson"
                :readonly="form.ourRepresentativesInfoFilled"
                required
              >
                <template #suffix>
                  <el-button size="mini" @click="openOurRepresentativesDialog">
                    <i class="el-icon-search"></i>
                  </el-button>
                </template>
              </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
            <el-form-item label="制单人员">
              <el-input v-model="form.documentMakers" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="制单日期">
              <el-date-picker v-model="form.documentDate" type="date" placeholder="选择日期" disabled></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注">
              <el-input type="textarea" v-model="form.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
    </el-card>

    <!-- 设备清单 -->
    <el-card title="设备清单">
      <div class="table-operations">
        <el-button type="primary" size="small" @click="addProductRow">增行</el-button>
        <el-button size="small" @click="deleteRow(productList)">删行</el-button>
      </div>

      <el-table 
        :data="productList" 
        border 
        style="width: 100%" 
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50px" v-model="multipleSelection.product"></el-table-column>
        <el-table-column type="index" label="序号" width="60px"></el-table-column>
        <el-table-column label="产品名称">
          <template #default="{ row }">
            <el-input
              v-model="row.equipmentName"
              :readonly="row.productInfoFilled"
            >
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="规格型号">
          <template #default="{ row }">
            <el-input v-model="row.specificationsModels" :disabled="row.productInfoFilled"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="设备数量">
          <template #default="scope">
            <el-input v-model="scope.row.equipmentNum"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 人员清单 -->
    <el-card title="人员清单">
      <div class="table-operations">
        <el-button type="primary" size="small" @click="addPersonnelRow">增行</el-button>
        <el-button size="small" @click="deleteRow(personnelList)">删行</el-button>
      </div>

      <el-table 
        :data="personnelList" 
        border 
        style="width: 100%" 
        @selection-change="handlePersonnelSelectionChange"
      >
        <el-table-column type="selection" width="50px" v-model="multipleSelection.personnel"></el-table-column>
        <el-table-column type="index" label="序号" width="60px"></el-table-column>
        <el-table-column label="人员岗位">
          <template #default="{ row }">
            <el-input
              v-model="row.personnelPositions"
              :readonly="row.productInfoFilled"
            >
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="定额能力">
          <template #default="{ row }">
            <el-input v-model="row.quorumCapacity" :disabled="row.productInfoFilled"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="作业人数">
          <template #default="scope">
            <el-input v-model="scope.row.numberWorkers"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </el-card>


   <!-- 我方代表选择对话框 -->
   <el-dialog
      v-model="ourRepresentativesDialogVisible"
      width="500px"
      title="我方代表选择"
      append-to-body
    >
      <el-table
        :data="ourRepresentativesList"
        highlight-current-row
        border
        size="small"
        @current-change="handleOurRepresentativesChange"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column property="userName" label="代表姓名" />
        <el-table-column property="depmentName" label="部门" />
        <el-table-column property="roleName" label="职位" />
      </el-table>
      <template #footer>
        <el-button @click="ourRepresentativesDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="pickOurRepresentatives">确定</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { write, read } from '@/axios/axiosHelper';
import { useCounterStore } from '@/stores/counter'

const store = useCounterStore();

// 表单验证规则
const rules = reactive({
  processName: [{ required: true, message: '请输入生产工序名称', trigger: 'blur' }],
  processType: [{ required: true, message: '请选择生产工序类别', trigger: 'change' }],
  capacityBody: [{ required: true, message: '请选择产能主体', trigger: 'change' }],
  processPerson: [{ required: true, message: '请输入工序负责人', trigger: 'blur' }]
});

// 基本信息表单数据
const form = ref({
  processName: "",
  processNumber: "",
  processType: "",
  capacityBody: true,
  processPerson: "",
  ourRepresentativesInfoFilled: false,
  documentMakers: "admin",
  documentDate: new Date(),
  remark: "",
  ordersId: 0,
});

// 设备清单数据
const productList = ref([{
  equipmentName: "",
  specificationsModels: "",
  equipmentNum: 0,
  processId: 0
}]);

// 人员清单数据
const personnelList = ref([{
  personnelPositions: "",
  quorumCapacity: "",
  numberWorkers: 0,
  processId: 0
}]);

// 表单ref
const formRef = ref(null);

// 选中行管理
const multipleSelection = ref({
  product: [],
  personnel: []
});

const handleSelectionChange = (val) => {
  multipleSelection.value.product = val;
};

const handlePersonnelSelectionChange = (val) => {
  multipleSelection.value.personnel = val;
};

// 设备清单增行方法
const addProductRow = () => {
  productList.value.push({
    equipmentName: "",
    specificationsModels: "",
    equipmentNum: 0,
    processId: 0
  });
  console.log('Added row to productList:', productList.value);
  // 添加延迟操作，确保数据正确更新
  nextTick(() => {
    console.log('After nextTick, productList:', productList.value);
  });
};

// 人员清单增行方法
const addPersonnelRow = () => {
  personnelList.value.push({
    personnelPositions: "",
    quorumCapacity: "",
    numberWorkers: 0,
    processId: 0
  });
  console.log('Added row to personnelList:', personnelList.value);
  // 添加延迟操作，确保数据正确更新
  nextTick(() => {
    console.log('After nextTick, personnelList:', personnelList.value);
  });
};

// 通用删行方法
const deleteRow = (list) => {
  let selection;
  if (list === productList) {
    selection = multipleSelection.value.product;
  } else if (list === personnelList) {
    selection = multipleSelection.value.personnel;
  }
  if (selection.length > 0) {
    list.value = list.value.filter(row => 
      !selection.includes(row)
    );
    ElMessage.success('删除成功');
  } else {
    ElMessage.warning('请先选择要删除的行');
  }
};

// 保存主表单和明细
const saveAll = async () => {
  if (!formRef.value) return;

  const isValid = await formRef.value.validate();
  if (!isValid) return;

  try {
    // 保存主表单
    const mainResponse = await write.post(
      'w-write/api/Process/AddProcess',
      form.value
    );

    if (mainResponse.data.code === 100) {
      ElMessage.success('主表单保存成功');
      const processId = mainResponse.data.data.processId;

      // 保存设备明细数据
      const productDetailPromises = productList.value.map(async (row) => {
        const detailData = {
          ...row,
          processId: processId
        };
        return write.post(
          'w-write/api/Process/AddEquipment',
          detailData
        );
      });

      await Promise.all(productDetailPromises);
      ElMessage.success('设备明细保存成功');

      // 保存人员明细数据
      const personnelDetailPromises = personnelList.value.map(async (row) => {
        const detailData = {
          ...row,
          processId: processId
        };
        return write.post(
          'w-write/api/Process/AddPersonnel',
          detailData
        );
      });

      await Promise.all(personnelDetailPromises);
      ElMessage.success('人员明细保存成功');
    } else {
      ElMessage.error(`主表单保存失败：${mainResponse.data.message}`);
    }
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存过程中发生错误，请检查网络或联系管理员');
  }
};

// 我方代表列表
const ourRepresentativesList = ref([]);
const currentOurRepresentative = ref(null);
const ourRepresentativesDialogVisible = ref(false);

// 生命周期钩子
onMounted(() => {
  fetchBaseData();
});

// 获取基础数据
const fetchBaseData = () =>{
// 工序负责人
read.get('read/api/Depment/GetDepUserRole')
    .then(res => ourRepresentativesList.value = res.data.data || [])
    .catch(error => {
      ElMessage.error('加载我方代表失败');
      console.error(error);
    });
}

// 打开工序负责人对话框
const openOurRepresentativesDialog = () => {
  if (ourRepresentativesList.value.length === 0) {
    ElMessage.warning('工序负责人数据加载中，请稍后重试');
    return;
  }
  ourRepresentativesDialogVisible.value = true;
};

// 处理工序负责人行选中
const handleOurRepresentativesChange = (val) => {
  currentOurRepresentative.value = val;
};

// 选择工序负责人并填充数据
const pickOurRepresentatives = () => {
  if (currentOurRepresentative.value) {
    form.value.processPerson = currentOurRepresentative.value.userName;
    form.value.ourRepresentativesInfoFilled = true;
    ourRepresentativesDialogVisible.value = false;
  } else {
    ElMessage.warning('请选择一个我方代表');
  }
};


</script>

<style scoped>
.outer-order-page {
  padding: 20px;
}

.table-operations {
  margin: 10px 0 20px;
  display: flex;
  gap: 8px;
}

.el-form-item {
  margin-bottom: 12px;
}

.el-table {
  margin-top: 15px;
}

.el-input__append {
  padding-right: 8px;
}
</style>    